#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>

#ifndef _WIN32
#include <unistd.h>
#define sleep(mill) usleep(mill*1000);
#endif

#include "anet.h"

#define BUFF_SIZE 512

void curlBaidu()
{
    char *error = calloc(BUFF_SIZE, sizeof(char));
    char *ips = calloc(BUFF_SIZE, sizeof(char));
    char data[] = "HEAD /index.html HTTP/1.1\nHost: baidu.com\nConnection: close\n\n";
    int fd = 0;

    anetInit();

    do
    {
        int ret = anetResolve(error, "baidu.com", ips, BUFF_SIZE);
        if (ret != ANET_OK)
        {
            printf("resolve error: %s\n", error);
            break;
        }

        printf("resolve: %s\n", ips);

        fd = anetTcpConnect(error, ips, 80);
        if (fd == ANET_ERR)
        {
            printf("connect error: %s,%d\n", error, fd);
            break;
        }

        if (anetEnableTcpNoDelay(error, fd) == ANET_ERR)
        {
            printf("nodelay error: %s,%d\n", error, fd);
            break;
        }

        if (anetWrite(fd, data, strlen(data)) == ANET_ERR)
        {
            printf("write error: %s,%d\n", error, fd);
            break;
        }

        int resp_len = 300;
        char *resp = calloc(resp_len, sizeof(char));
        if (anetRead(fd, resp, resp_len) == ANET_ERR)
        {
            printf("read error: %s,%d\n", error, fd);
            break;
        }

        resp[resp_len - 1] = '\0';
        printf("%s\n", resp);
    } while (0);

    anetClose(fd);
    free(ips);
    free(error);
}

int echoServer()
{
    char hi[] = {"hello\n"};
    int ipfd = anetTcpServer(NULL, 8000, "0.0.0.0", 0);
    assert(ipfd != ANET_ERR);
    printf("server listen on 8000\n");

    int client_port, client_fd;
    char client_ip[128];
    client_fd = anetTcpAccept(NULL, ipfd, client_ip, 128, &client_port);
    printf("Accepted %s:%d\n", client_ip, client_port);

    anetWrite(client_fd,hi,sizeof(hi));

    sleep(500);
    anetClose(client_fd);
    anetClose(ipfd);

    return 0;
}

int main(int argc, char **argv)
{
    curlBaidu();
    echoServer();
    return 0;
}
